<!-- 用户管理 - 弹框 -->
<template>
    <el-dialog 
    :title="typeTitle+'用户'"
    v-model="dialogVisible"
    width="45%"
    :close-on-click-modal="false" 
    :close-on-press-escape="true"
    @closed="resetForm(formRef)">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
            <el-form-item label="用户名" prop="userId">
                <el-input v-model="form.userId" :readonly="billState" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="userId">
                <el-input v-model="form.nickname" :readonly="billState" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
                <el-input v-model="form.phoneNumber" :readonly="billState" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="eMail">
                <el-input v-model="form.eMail" :readonly="billState" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="showPassword" v-if="addType">
                <el-input type="password" show-password v-model="form.showPassword" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-row>
                <el-col :md="24" :lg="12">
                    <el-form-item label="角色" prop="roles">
                        <el-select multiple :disabled="billState" v-model="form.roles" placeholder="请选择用户角色">
                            <el-option 
                            v-for="item in roleList" 
                            :key="item.id" 
                            :label="item.roleName" 
                            :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="24" :lg="12">
                    <el-form-item label="状态" prop="">
                        <el-radio-group :disabled="billState" v-model.number="form.state">
                            <el-radio v-for="item in stateList" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span>
                <el-button type="primary" class="" v-if="dialogState == 'add'" :loading="submitLoading" @click="submitClick">确定</el-button>
                <el-button type="primary" class="" v-if="dialogState == 'update'" :loading="updateLoading" @click="updateClick">确定</el-button>
                <el-button class="" @click="resetForm(formRef)">关闭</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { computed, nextTick, reactive, ref } from "vue";

import { rolesApi } from '@/api/system/roles/roles-api';
import { usersApi } from '@/api/users/users/users-api';

import { aes } from '@/utils/crypto-util';
import { montageStr } from '@/utils/tools-util';

import { ElMessage } from 'element-plus';


// ========================= 弹框控制 =========================
let dialogVisible = ref(false);
let dialogState = ref('add');
function onShowDialog(type, row) {
    getRoleList();
    if(row) {
        for(let key in form) {
            form[key] = row[key];
        };
        form.roles = montageStr(row.roles, 'id');
        form.id = row.id;
    }
    dialogState.value = type;
    dialogVisible.value = true;
};

// 组件向外暴露属性或方法
defineExpose({
    onShowDialog
});

// ========================= 计算属性 =========================
const typeTitle = computed(() => {
    if(dialogState.value == 'add') return '新增';
    if(dialogState.value == 'update') return '修改';
    if(dialogState.value == 'view') return '查看';
});

const addType = computed(() => {
    if(dialogState.value == 'add') return true;
});

const billState = computed(() => {
    if(dialogState.value != 'view') return false;
    return true;
});

// ========================= 定义发射给父组件的方法 =========================
const emits = defineEmits(['updateUsersList']);

// ========================= 表单 =========================
const form = reactive({
    id:'',              // 主键
    userId:'',          // 用户名
    slogan:'',          // 格言
    sex:0,              // 性别
    nickname:'',        // 昵称
    avatar:'',          // 头像
    roles:[2],          // 角色
    showPassword:'',    // 展示密码
    password:'',        // 密码
    phoneNumber:'',     // 手机号
    eMail:'',           // 邮箱
    state:1,            // 状态
    createdAt:'',       // 创建时间
    updatedAt:'',       // 更新时间
});
const rules = reactive({
    userId: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' }
    ],
    // eMail: [
    //     { required: true, message: '请输入邮箱', trigger: 'blur' },
    //     { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    // ],
    showPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    roles: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
    ],
});
let stateList = reactive([
    {label: '正常', value: 1},
    {label: '停用', value: 0},
]);

// 表单操作
const formRef = ref();
let submitLoading = ref(false);
// 提交
function submitClick() {
    formRef.value.validate(async (valid) => {
        try {
            if(valid) {
                submitLoading.value = true;
                let date = new Date();
                let password = aes.en(form.showPassword);
                form.createdAt = date;
                form.updatedAt = date;
                form.password = password;
                delete form.id;
                const res = await usersApi.create(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('新增成功');
                submitLoading.value = false;
                dialogVisible.value = false;
                emits('updateUsersList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            submitLoading.value = false;
        };
    });
};

// 更新
let updateLoading = ref(false);
function updateClick() {
    formRef.value.validate(async (valid) => {
        console.log(valid)
        try {
            if(valid) {
                updateLoading.value = true;
                let date = new Date();
                form.updatedAt = date;
                const res = await usersApi.update(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('修改成功');
                updateLoading.value = false;
                dialogVisible.value = false;
                emits('updateUsersList');
            };
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message);
        } finally {
            updateLoading.value = false;
        }
    })
};

// 获取角色列表
let roleList = ref([]); // 角色列表
async function getRoleList() {
    let conditions = {
        params: {
            state: true
        }
    }
    const res = await rolesApi.list(conditions);
    roleList.value = res.data.data;
};


// ========================= 重置表单 =========================
function resetForm(refFormName) {
    refFormName.resetFields(); // 重置表单
    for(let key in form) {
        form[key] = '';
    };
    form.roles = [2];
    form.state = 1;
    form.sex = 0;
    dialogVisible.value = false;
};

</script>

<style lang="scss" scoped>

</style>